<template>
  <div class="import">
    <el-card>
      <h3>员工导入</h3>
      <el-alert
        show-icon
        title="每次导入仅可添加1000名员工，姓名、手机、入职时间、聘用形式为必填项"
        type="warning"
      >
      </el-alert>
      <upload-excel :beforeUpload="beforeUpload" :onSuccess="onSuccess" />
    </el-card>
  </div>
</template>

<script>
import UploadExcel from "@/components/UploadExcel";
import { addAllUserApi } from "@/api/employees";
export default {
  components: {
    UploadExcel,
  },
  methods: {
    beforeUpload(file) {
      //判断文件的大小 flie.size b
      console.log(file);
      const less2M = file.size / 1024 / 1024 < 2;
      if (!less2M) {
        this.$message.error("文件大小超过了2M");
      }
      return less2M;
    },
    async onSuccess({ header, results }) {
      console.log({ header, results });
      //定义中文属性对应的英文属性
      var obj = {
        入职日期: "timeOfEntry",
        姓名: "username",
        工号: "workNumber",
        手机号: "mobile",
        转正日期: "correctionTime",
      };
      //将中文的属性改为英文的属性
      const newArr = results.map((item) => {
        var newObj = {};
        Object.keys(obj).forEach((subitem) => {
          //subitem :上面obj的键(入职时间&姓名...)
          if (
            obj[subitem] === 'timeOfEntry' ||
            obj[subitem] === 'correctionTime'
          ){
            // 将天数据转为时间
            newObj[obj[subitem]] = this.formatData(item[subitem])
          }else {
            newObj[obj[subitem]] = item[subitem]
          }
        });
        console.log('返回数据',newObj);
        return newObj;
      });
      
      //将数据提交到服务器
      await addAllUserApi(newArr);
      //提示上传成功
      this.$message.success("上传成功");
      //提交上传成功,返回到员工列表
      this.$router.push("/employees");
    },
    //转换时间:将excel 中的具体天数转为具体时间
    formatData(days) {
      //将天数转为时间戳
      var timestemp = (days - 1) * 24 * 60 * 60 * 1000
      // 在讲时间戳转为具体时间
      var time = new Date(timestemp);
      //年份多出70年,还要减去70年
      time.setFullYear(time.getFullYear() - 70);
      console.log('时间',time);
      return time;

    },
  },
};
</script>

<style>
</style>